package com.pospi.pai.yunpos.report;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;
import com.pospi.util.GetData;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.formatter.ColumnChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleColumnChartValueFormatter;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.LineChartView;
import lib.kingja.switchbutton.SwitchMultiButton;

public class XsColumReportActivity extends Base2Activity {
    @Bind(R.id.switch_button)
    SwitchMultiButton switch_button;

    @Bind(R.id.tv_lx)
    TextView tv_lx;
    @Bind(R.id.tv_md)
    TextView tv_md;
    @Bind(R.id.time_start_select)
    TextView time_start_select;
    @Bind(R.id.time_end_select)
    TextView time_end_select;
    @Bind(R.id.column_chart)
    ColumnChartView column_chart;
    @Bind(R.id.column_chart2)
    ColumnChartView column_chart2;
    @Bind(R.id.ll_lx)
    LinearLayout ll_lx;
    @Bind(R.id.ll_md)
    LinearLayout ll_md;

    private String thje;
    private String zje;
    private String xsje;
    private List<SupBeen> lx_Beens = new ArrayList<>();//类型
    private List<SyyBeen> syy_Beens = new ArrayList<>();//收银员
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    private String syyname;
    String[] date = {"5-23","5-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","1-22","6-22","5-23","5-22","2-22","5-22","4-22","9-22","10-22","11-22","12-22","4-22","9-22","10-22","11-22","zxc"};//X轴的标注
    int[] score= {74,22,18,79,20,74,20,74,42,90,74,42,90,50,42,90,33,10,74,22,18,79,20,74,22,18,79,20};//图表的数据
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.fragment_xs_colum);
        ButterKnife.bind(this);
        setTitle(SPHelper.getInstance().getString(Constant.STORE_NAME)+"收银员销售对比图");
        time_start_select.setText(GetData.getYYMMDDTime());
        time_end_select.setText(GetData.getYYMMDDTime());
        new BillUtil().initBilltype(lx_Beens);
        ll_lx.setVisibility(View.GONE);
        ll_md.setVisibility(View.GONE);
        init();
        down();
//        downmd();

    }


    @OnClick({R.id.tv_lx,R.id.tv_md,  R.id.bt_search, R.id.time_start_select, R.id.time_end_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_lx:
//                showlx(tv_lx);
                break;
            case R.id.tv_md:
//                showmd(tv_md);
                break;
            case R.id.bt_search:
                searchBillfast();
                switch_button.clearSelection();
                break;
            case R.id.time_start_select:
                showDate(time_start_select);
                break;
            case R.id.time_end_select:
                showDate(time_end_select);
                break;
        }
    }

    private void init() {

        switch_button.setText("今天", "昨天", "近三天", "近七天", "本月");
        switch_button.setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                switch (position) {
                    case 0:
                        startrq = GetData.getAnyTime(0);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 1:
                        startrq = GetData.getAnyTime(1);
                        endrq = GetData.getAnyTime(1);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 2:
                        startrq = GetData.getAnyTime(3);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 3:
                        startrq = GetData.getAnyTime(7);
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;
                    case 4:
                        startrq = GetData.getFirstDate();
                        endrq = GetData.getAnyTime(0);
                        time_start_select.setText(startrq);
                        time_end_select.setText(endrq);
                        searchBillfast();
                        break;


                }
            }
        });

        searchBillfast();


    }

    private String market = "";
    private String type = "";
    private String syyid = "";

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeLodindDialog();
                    if (topBeens.size() == 0) {
                        setbill(false);
                    } else {
                        setHistoryChart(topBeens,Color.parseColor("#B0E0E6"),column_chart ,"je");
                        setHistoryChart(topBeens,Color.parseColor("#4682B4"),column_chart2,"sl");
                        setbill(true);
                    }

                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };

    private void setbill(boolean o) {
        if (o) {
//            bill_num_title.setVisibility(View.VISIBLE);
//            tv_list_title.setText("总销售额：");
//            total_je.setText(je);
//            bill_num.setText("" + count);
//            tv_xs.setText(xsje);
//            tv_th.setText(thje);
//            tv_hjje.setText(zje);

        } else {
            Toast.makeText(this, "未查询到信息", Toast.LENGTH_SHORT).show();
//            total_je.setText("");
//            bill_num.setText("");
//            tv_xs.setText("0");
//            tv_th.setText("0");
//            tv_hjje.setText("0");
            topBeens.clear();
        }

    }



    private String startrq = GetData.getAnyTime(0);
    private String endrq = GetData.getAnyTime(0);

    private void searchBillfast() {
        showLodingDialog("请求中...");
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "pos.Mreport");
        params.put("fun", "find_syyxsdb");
        JSONObject object = new JSONObject();
        try {
            object.put("startrq", time_start_select.getText().toString());
            object.put("endrq", time_end_select.getText().toString());
            object.put("market", SPHelper.getInstance().getString(Constant.STORE_ID));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    Log.i("login", jsonObject.getString("errMsg"));
                    JSONArray result = jsonObject.getJSONArray("result");
                    getResult(result);
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }
        });

    }

    List<XsSyyBeen> topBeens = new ArrayList<>();

    private void getResult(JSONArray result) {
        topBeens.clear();
        for (int i = 0; i < result.length(); i++) {
            try {
                JSONObject object = result.getJSONObject(i);
                XsSyyBeen been = new Gson().fromJson(object.toString(), XsSyyBeen.class);
                topBeens.add(been);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    //下载收银员
    private void down() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getsyy");
        params.put("market", SPHelper.getInstance().getString(Constant.STORE_ID));
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    syy_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SyyBeen>>() {
                    }.getType());
                    syy_Beens.add(new BillUtil().getNewSyy());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    //下载
    private void downmd() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());

                    md_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }


    private void showmd(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SyyBeen been : syy_Beens) {
            strings.add(been.getSyyname());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_md.setText(syy_Beens.get(position).getSyyname());
                syyid = syy_Beens.get(position).getSyyid();
                syyname = syy_Beens.get(position).getSyyname();
                yyyPopupWindow.dismiss();
            }
        });
    }


    private void showlx(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : lx_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_lx.setText(lx_Beens.get(position).getName());
                type = lx_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }

    private void showDate(final TextView tv) {
        final Calendar c = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(XsColumReportActivity.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                c.set(year, monthOfYear, dayOfMonth);
                tv.setText(DateFormat.format("yyyy-MM-dd", c));

            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }


    private void setHistoryChart( List<XsSyyBeen> beens,int columnColor, ColumnChartView charView ,String type) {
        // 每列1个subcolumn。
        int numSubcolumns = 1;
        //定义一个圆柱对象集合
        List<Column> columns = new ArrayList<Column>();
        //子列数据集合
        List<SubcolumnValue> values;
        List<AxisValue> axisValues = new ArrayList<AxisValue>();
        //遍历列数numColumns
        for (int i = 0; i < beens.size(); ++i) {
            values = new ArrayList<SubcolumnValue>();
            //遍历每一列的每一个子列
            for (int j = 0; j < numSubcolumns; ++j) {
                //为每一柱图添加颜色和数值
                values.add(new SubcolumnValue(type.equals("je")?beens.get(i).getXsjje():beens.get(i).getXsbs(), columnColor));
            }
            //创建Column对象
            Column column = new Column(values);
            ColumnChartValueFormatter chartValueFormatter = new SimpleColumnChartValueFormatter(0);
            column.setFormatter(chartValueFormatter);
            //是否有数据标注
            column.setHasLabels(true);
            //是否是点击圆柱才显示数据标注
            column.setHasLabelsOnlyForSelected(false);
            columns.add(column);
            //给x轴坐标设置描述
            axisValues.add(new AxisValue(i).setLabel(beens.get(i).getSyyname()));
        }
        //创建一个带有之前圆柱对象column集合的ColumnChartData
        ColumnChartData data = new ColumnChartData(columns);
        data.setValueLabelTextSize(15);
        data.setValueLabelBackgroundColor(Color.parseColor("#48D1CC"));
//        data.setValueLabelTypeface(Typeface.DEFAULT);// 设置数据文字样式
        data.setValueLabelBackgroundEnabled(true);
        data.setValueLabelBackgroundAuto(false);
        //定义x轴y轴相应参数
        Axis axisX = new Axis();
        Axis axisY = new Axis();
//        axisY.setName("数量");//轴名称
//        axisY.hasLines();//是否显示网格线
        axisY.setTextColor(Color.parseColor("#333333"));//颜色
        axisX.hasLines();
        axisX.setTextColor(Color.parseColor("#333333"));
        axisX.setValues(axisValues);
        axisX.setTextSize(16);
        axisX.setHasSeparationLine(true);
        //把X轴Y轴数据设置到ColumnChartData 对象中
        data.setAxisXBottom(axisX);
        data.setAxisYLeft(axisY);
        //给表填充数据，显示出来
        charView.setInteractive(false);
        charView.setColumnChartData(data);
    }


}
